package com.mybatisplus.demo.base;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * @CLASSNAME CreateOptional
 * @DESCRIPTION 描述
 * @AUTHOR chen
 * @DATE 2019-10-25 23:51
 **/
public class CreateOptional {

    public static void main(String[] args) throws IOException {


        String content = new String(Files.readAllBytes(Paths.get("d:\\profile\\word.txt")), StandardCharsets.UTF_8);
        List<String> wordsList = Arrays.asList(content.split("\\PL+"));

        Optional<String> optionalS = wordsList.stream().filter(s -> s.contains("a")).findFirst();
        System.out.println(optionalS.orElse("NO word") + "contain fred");

        Optional<String> stringOptional = Optional.empty();
        String result = stringOptional.orElse("N/A");
        System.out.println("result:" + result);

        result = stringOptional.orElseGet(() -> Locale.getDefault().getDisplayLanguage());
        System.out.println("result:" + result);
        try {
            result = stringOptional.orElseThrow(IllegalStateException::new);
            System.out.println("result:" + result);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        optionalS = wordsList.stream().filter(s -> s.contains("world")).findFirst();
        optionalS.ifPresent(s -> System.out.println(s + "contain world"));

        Set<String> results = new HashSet<>();
        optionalS.ifPresent(results::add);
        Optional<Boolean> added = optionalS.map(results::add);
        System.out.println(added);

        System.out.println(inverse(4.0).flatMap(CreateOptional::square));
        System.out.println(inverse(-1.0).flatMap(CreateOptional::square));
        System.out.println(inverse(0.00).flatMap(CreateOptional::square));
        Optional<Double> results2 = Optional.of(-4.0).flatMap(CreateOptional::inverse).flatMap(CreateOptional::square);
        System.out.println(results2);
    }

    private static Optional<Double> inverse(Double x) {
        return x == 0 ? Optional.empty() : Optional.of(1 / x);
    }

    private static Optional<Double> square(Double x) {
        return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
    }
}
